package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {


    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 图片上传
     * @param multipartFile
     * @return
     */

    @Override
    public ResponseResult uploadPiture(MultipartFile multipartFile) throws IOException {

        // 1.参数校验
        if(multipartFile == null || multipartFile.getSize() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2.上传图片
        // 2.1图片名称
        String filename = UUID.randomUUID().toString().replace("-", "");
        // 获取文件后缀名称
        String originalFilename = multipartFile.getOriginalFilename();
        String postFix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileId = fileStorageService.uploadImgFile("", filename + postFix, multipartFile.getInputStream());

        // 3.保存到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setType((short) 1);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 图片列表
     * @param wmMaterialDto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto wmMaterialDto) {
        // 1.参数校验
        wmMaterialDto.checkParam();

        //2.分页查询
        Page<WmMaterial> page = new Page<>(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        LambdaQueryWrapper<WmMaterial> wmMaterialLambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 检查是否收藏
        if(wmMaterialDto.getIsCollection() != null && wmMaterialDto.getIsCollection() == 1){
            wmMaterialLambdaQueryWrapper.eq(WmMaterial::getIsCollection, wmMaterialDto.getIsCollection());
        }

        // 查询这个用户的素材
        wmMaterialLambdaQueryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());

        // 按照时间倒序排列
        wmMaterialLambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        page = page(page, wmMaterialLambdaQueryWrapper);

        // 3.结果返回
        PageResponseResult pageResponseResult = new PageResponseResult(wmMaterialDto.getPage(), wmMaterialDto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;
    }

    /**
     * 取消收藏
     * @param id 素材ID
     * @return 操作结果
     */
    @Override
    public ResponseResult cancelCollect(Long id) {
        // 1. 参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2. 查询数据库中该素材是否存在并属于当前用户
        Long userId = Long.valueOf(WmThreadLocalUtil.getUser().getId());
        WmMaterial wmMaterial = getOne(
                new LambdaQueryWrapper<WmMaterial>()
                        .eq(WmMaterial::getId, id)
                        .eq(WmMaterial::getUserId, userId)
        );

        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "素材不存在或不属于当前用户");
        }

        // TODO 不能将未收藏改为收藏
        // 3. 修改收藏状态为 0（取消收藏）
        short collecId = wmMaterial.getIsCollection();
        if (collecId == 0) {
            wmMaterial.setIsCollection((short) 1);
        } else if (collecId == 1) {
            wmMaterial.setIsCollection((short) 0);
        } else {
            // 处理异常情况，默认设为收藏
            wmMaterial.setIsCollection((short) 0);
        }

        updateById(wmMaterial);

        // 4. 返回成功结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
